# Create your views here.
from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection

from utils.captcha.captcha.captcha import captcha


class ImageCodeView(View):
    def get(self, request, uuid):
        # 步骤
        # 1获取uuid
        print(uuid)
        # 2生成图片验证码 和二进制图片数据
        text, image = captcha.generate_captcha()
        print(text)
        # 3redis保存验证码 用uuid为key 有效期
        redis_cli = get_redis_connection('code')
        # uuid为key 120是过期时间
        redis_cli.setex(uuid, 120, text)
        # 返回二进制图片数据

        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeview(View):
    def get(self, request, mobile):
        # 1获取参数
        image_code = request.GET.get("image_code")  # 图片验证
        uuid = request.GET.get("image_code_id")  # uuid
        # 2验证参数
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # 3 验证图片验证码
        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)
        try:
            redis_cli.delete(uuid)
        except Exception as  e:
            print('删除图片验证码')
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': '图片验证码过期'})
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({'code': 400, 'errmsg': '图片验证码输入错误'})
        print('hehe')
        # 4生成短信验证码
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        print('sms_code', sms_code)

        # 防止发送频繁
        # 1 获取'send_flag_手机号的值
        send_flag = redis_cli.get('send_flag_%s' % mobile)
        # 2 如果值存在 返回错误响应 过于频繁发送
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁 csk'})
        # 创建redis管道
        pl = redis_cli.pipeline()
        # 将redis请求添加到队列
        # 5保存短信验证码 到redis key的格式 sms_手机号
        pl.setex("sms_%s" % mobile, 300, sms_code)
        # 3 保存send_flag_手机号的值
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        # 6发送短信
        from utils.sms.sms_util import SmsUtil
        SmsUtil().send_message(mobile, (sms_code, 5))
        return JsonResponse({'code': 0, 'errmsg': "ok"})
